var express = require('express');
var path = require('path');

var logger = require('morgan');
var app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

// 注册跨域中间件
app.use(require('cors')())


//注册返回信息的中间件
app.use((req, res, next) => {
    //封装返回数据的函数
    res.cc = function (status = 200, msg = '', data = []) {
        res.json({
            status,
            msg,
            data
        })
    }
    //注册属性
    //req.host = req.protocol + '://' + req.hostname + ':' + process.env.PORT
    next()
})


//注册验证用户是否登录的中间件
const {
    expressjwt: expressJwt
} = require('express-jwt')
//旧版本直接使用
//const expressJwt=require('express-jwt')
app.use(expressJwt({
    secret: 'kuaijian', //同加密的秘钥
    algorithms: ['HS256']
}).unless({
    //排除掉不需要做jwt验证的路由前缀
    path:[/^\/api\//]
}))


var indexRouter = require('./routes/home');
var listRouter = require('./routes/home/list');
var cateRouter=require('./routes/home/cate')
var newRouter=require('./routes/home/new')
var userRouter=require('./routes/home/user')
var commentRouter=require('./routes/home/comment')


app.use('/api', indexRouter);
app.use('/api', listRouter);
app.use('/api',cateRouter);
app.use('/api',newRouter);
app.use('/api',userRouter);
//评论
app.use('/my',commentRouter);

//验证登录接口
app.post('/my/checklogin',(req,res)=>{
    res.cc(200,'登录成功',req.auth.user_name)
})


// 注册全局错误级别中间件中，捕获验证失败的错误，并把验证失败的结果响应给客户端
app.use(function (err, req, res, next) {
    // 数据验证失败
    //if (err instanceof joi.ValidationError) return res.cc(400, err.message)
    //jwt验证失败
     //如果是解析token的错误,提示解析错误相关
     if (err.name === 'UnauthorizedError') {
         /* return res.json({
               status:401,
               msg:'token无效'
            }) */
          return res.cc(401,err.message);  
     }
    // 未知错误
     res.cc(500,err.message)
})



module.exports = app;
